<template>
  <el-card style="max-width: 600px; margin: 20px auto">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="个人信息" name="info">
        <el-form :model="profileForm" label-width="100px">
          <el-form-item label="用户名">
            <el-input v-model="profileForm.username" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="profileForm.email" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveProfile">保存</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="修改密码" name="password">
        <el-form :model="passwordForm" label-width="100px">
          <el-form-item label="旧密码">
            <el-input v-model="passwordForm.oldPassword" type="password" />
          </el-form-item>
          <el-form-item label="新密码">
            <el-input v-model="passwordForm.newPassword" type="password" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="changePassword">修改密码</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="修改头像" name="avatar">
        <el-form label-width="100px">
          <el-form-item label="头像上传">
            <el-upload
              class="avatar-uploader"
              :auto-upload="false"
              :file-list="fileList"
              :on-change="handleAvatarChange"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :limit="1"
              list-type="picture-card"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <el-button
              v-if="fileList.length > 0"
              type="primary"
              size="small"
              style="margin-top: 10px"
              @click="doUploadAvatar"
            >
              确认上传
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {me, updatePassword, updateUser, uploadAvatar} from '@/api/user.js'
import { useUserStore } from '@/stores/userStore.js'
import router from "@/router/index.js";

const activeTab = ref('info')
const userStore = useUserStore()

// 个人信息
const profileForm = ref({
  username: '',
  email: '',
  avatar: '',
})

// 修改密码
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
})

const fetchProfile = async () => {
  // 获取用户信息
  const profile = await me()
  const { username, email, avatar } = profile
  profileForm.value = { username, email, avatar }
}

// 保存个人信息
async function saveProfile() {
  try {
    await updateUser(profileForm.value)
    userStore.updateUserInfo(profileForm.value)
    ElMessage.success('信息已保存，请重新登录。')
    router.push('/login')
  } catch {
    ElMessage.error('保存失败')
  } finally {
    profileForm.value.username = ''
    profileForm.value.email = ''
  }
}

// 修改密码
async function changePassword() {
  try {
    await updatePassword(passwordForm.value)
    ElMessage.success('密码修改成功，请重新登录。')
    router.push('/login')
  } catch (err) {
    ElMessage.error(err.response.data.message || '修改密码失败')
  } finally {
    passwordForm.value.oldPassword = ''
    passwordForm.value.newPassword = ''
  }
}

// 头像上传
const fileList = ref([])
const selectedFile = ref(null)

function handleAvatarChange(file, fileListRaw) {
  selectedFile.value = file.raw
  fileList.value = fileListRaw
}

function handleRemove() {
  selectedFile.value = null
  fileList.value = []
}

function beforeUpload(file) {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) ElMessage.error('只能上传图片文件')
  if (!isLt2M) ElMessage.error('大小不能超过 2MB')
  return isImage && isLt2M
}

async function doUploadAvatar() {
  if (!selectedFile.value) {
    ElMessage.warning('请选择头像文件')
    return
  }

  const formData = new FormData()
  formData.append('file', selectedFile.value)

  try {
    const url = await uploadAvatar(formData)
    profileForm.value.avatar = url
    userStore.updateAvatar(url)
    ElMessage.success('上传成功')

    fileList.value = []
    selectedFile.value = null
  } catch (err) {
    ElMessage.error('上传失败')
  }
}

onMounted(() => {
  fetchProfile()
})
</script>

<style scoped>
.avatar-uploader .el-upload {
  width: 100px;
  height: 100px;
}
</style>
